import { TGameObject, TGameObjectOptions } from './tGameObject';
import { measureText } from '../utils';
import { fontStyleObjToStr } from '../engine-utils';
import { drawText } from '../renderer';

export interface TextStyle {
  fontStyle?: string;
  fontVariant?: string;
  fontWeight?: string;
  fontSize?: number;
  lineHeight?: string;
  fontFamily?: string;
}

export type TextAlign = 'start'|'end'|'left'|'right'|'center';

export type TextBaseline = 'top'|'hanging'|'middle'|'alphabetic'|'ideographic'|'bottom';

export interface TextOptions extends Omit<TGameObjectOptions, 'width' | 'height'> {
  text: string;
  color: string;
  stroke?: string;
  fontStyle?: TextStyle;
  textAlign?: TextAlign;
  textBaseline?: TextBaseline;
}

export class Text extends TGameObject {
  private _text: string;

  get text () { return this._text; }

  set text (value: string) {
    const { width, height } = measureText(value, fontStyleObjToStr(this.fontStyle), this.stroke);
    this.width = width;
    this.height = height;
    this._text = value;
  }

  public fontStyle: TextStyle;

  public color: string;

  public stroke: string;

  public textAlign: TextAlign;

  public textBaseline: TextBaseline;

  constructor (options: TextOptions) {
    const { text, color, stroke, fontStyle } = options;
    const { width, height } = measureText(text, fontStyleObjToStr(fontStyle), stroke);
    super(Object.assign({ width, height, }, options));

    this.text = text;
    this.color = color;
    this.stroke = stroke;
    this.fontStyle = fontStyle;

    this.textAlign = 'left';
    this.textBaseline = 'top';
  }

  render (canvasCtx: CanvasRenderingContext2D) {
    drawText(canvasCtx, this);
  }
}
